package com.gzk.hrm.exception;

import com.gzk.hrm.util.AjaxResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.function.Consumer;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(GlobalException.class)
    public AjaxResult GlobalExceptionHandler(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        //处理错误信息
        StringBuilder sb = new StringBuilder();
        allErrors.forEach(new Consumer<ObjectError>() {
            @Override
            public void accept(ObjectError objectError) {
                sb.append(objectError.getDefaultMessage()).append(";");
            }
        });
        return AjaxResult.me().setSuccess(false).setMessage(sb.toString());
    }

    @ExceptionHandler(Exception.class)
    public AjaxResult ExceptionHandler(Exception e){
        e.printStackTrace();
        if(e.getClass().getSimpleName().equals("AccessDeniedException")){
            return AjaxResult.me().setSuccess(false).setMessage("没有权限访问！");
        }
        return AjaxResult.me().setSuccess(false).setMessage("系统繁忙！");
    }
}
